package com.example.hms.service.serviceImpl;
import com.example.hms.Dao.UserDao;
import com.example.hms.entity.SystemLog;
import com.example.hms.entity.User;
import com.example.hms.service.SystemLogService;
import com.example.hms.service.UserServive;
import com.example.hms.ulit.Result;
import com.example.hms.ulit.ResultSubmit;
import com.example.hms.ulit.TokenUtil;
import com.example.hms.ulit.UserResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 定义一个名为UserServiceImpl的服务实现类，该类实现了UserServive接口
@Service
@Transactional (propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class UserServiceImpl implements UserServive {
    // 使用@Resource注解自动注入UserDao对象，用于执行数据库操作
    @Resource
    UserDao userDao;
    SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    SystemLogService systemLogService;
    @Override
    public Result login(String userId, String userPassword, HttpServletRequest request) {

        User user = userDao.login(userId);
        if (user == null) {
            return ResultSubmit.error("登录失败，用户不存在");
        } else if (userPassword.equals(user.getUserPassword())) {
            HttpSession session = request.getSession();
            session.setAttribute("userId", user.getUserId());
            session.setAttribute("userName", user.getUserName());
            session.setAttribute("roleName", user.getRoleName());
            long time = System.currentTimeMillis();
            session.setAttribute("time", time);
            session.setAttribute("token", TokenUtil.getToken(
                    String.valueOf(user.getUserId()), user.getUserName(), user.getRoleName(), time
            ));
            // 系统记录
            SystemLog systemLog = new SystemLog();
            systemLog.setUserId(user.getUserId());
            systemLog.setRoleName(user.getRoleName());
            systemLog.setCreateTime(format.format(new Date()));
            systemLog.setUseTableName("user");
            systemLog.setUseTableDataIdBefore(String.valueOf(user.getUserTableId()));
            systemLog.setUseTableDataIdAfter(String.valueOf(user.getUserTableId()));
            systemLog.setUseType("用户登录");
            systemLogService.insert(systemLog);
            // 返回登录成功结果
            return ResultSubmit.success(sweet(user));
        } else {
            return ResultSubmit.error("登录失败，密码错误");
        }
    }

    private UserResult sweet(User user) {
        UserResult userResult = new UserResult();
        userResult.setUserId(user.getUserId());
        userResult.setUserName(user.getUserName());
        userResult.setRoleName(user.getRoleName());
        return userResult;
    }
    @Override
    public Result info(HttpServletRequest request) {
        // 获取HttpSession对象
        HttpSession session = request.getSession();
        // 从session中获取用户信息
        session.getAttribute("userId");
        session.getAttribute("userName");
        session.getAttribute("roleName");

        // 创建UserResult对象，用于封装返回的用户信息
        UserResult userResult = new UserResult();
        userResult.setUserId((Integer) session.getAttribute("userId"));
        userResult.setUserName(session.getAttribute("userName").toString());
        userResult.setRoleName(session.getAttribute("roleName").toString());

        // TODO: 系统记录，可能用于记录用户操作日志等
        return ResultSubmit.success(userResult);
    }
    @Override
    public Result selectAllUser(String UserId, String UserName, String RoleName){
        List<User> list = userDao.selectAllUser(UserId, UserName, RoleName);
        return ResultSubmit.success(list);
    }
    @Override
    public Result insert(User user) {
        user.setCreateTime(format.format(new Date()));
        user.setUserId(Math.abs((int)System.currentTimeMillis()));
        user.setRoleId(2);
        user.setDelete("未删除");
        int result = userDao.insert(user);
        if (result == 1) {
           return  ResultSubmit.success("成功");
        }else {
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }
    @Override
    public Result update(User user){
      int i = userDao.update(user);
        user.setCreateTime(format.format(new Date()));
        user.setDelete("未删除");
        user.setUserTableId(0);
        int j = userDao.insert(user);
        // todo 系统记录操作
        if (i == 1 || j == 1) {
            return ResultSubmit.success("成功");
        }else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }

    @Override
    public Result delete(String userId){
        User user = userDao.login(userId);
        int i = userDao.update(user);
        // todo 系统记录操作
        if (i == 1) {
            return ResultSubmit.success("成功");
        }else {
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultSubmit.error("失败");
        }
    }

}
